package cn.hnucm.searchesservice.dao.impl;

import cn.hnucm.searchesservice.dao.Dao;
import cn.hnucm.searchesservice.dao.TbGoodsBasisDao;
import cn.hnucm.searchesservice.entity.TbGoodsBasis;
import cn.hnucm.searchesservice.entity.TbGoodsImage;
import cn.hnucm.searchesservice.service.TbGoodsImageService;
import cn.hnucm.searchesservice.utils.MyInterId;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 商品表
 * @author: chenjintao
 * @Date: 2021/12/20 23:21
 */
@Controller
public class TbGoodsBasisDaoImpl implements TbGoodsBasisDao {

    @Autowired
    @Qualifier("getRestHighLevelClient")
    private RestHighLevelClient client;


    /**
     * 获取所有的商品信息
     * @return
     */
    @Override
    public List<TbGoodsBasis> getAllGoods() {
        SearchRequest request = new SearchRequest("tb_goods_basis");
        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.matchAllQuery());
        return getTbGoodsBases(request, builder);
    }

    /**
     * 根据商品号查询商品信息
     *
     * @param goodsId
     * @return
     */
    @Override
    public TbGoodsBasis getGoodsById(Integer goodsId) {
        GetRequest request = new GetRequest("tb_goods_basis", String.valueOf(goodsId));
        try {
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            TbGoodsBasis goodsBasis = new TbGoodsBasis();
            goodsBasis.setGoodsId(Integer.valueOf(response.getId()));
            if (response.getSource() == null) return null;
            loadingLog(goodsBasis, response.getSource());
            return goodsBasis;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 根据商品名称和商品简介模糊查询
     *
     * @param describe
     * @return
     */
    @Override
    public List<TbGoodsBasis> getGoodsByDescribe(String describe) {
        SearchRequest request = new SearchRequest("tb_goods_basis");
        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery()
                        .should(QueryBuilders.matchQuery("goodsName",describe))
                        .should(QueryBuilders.matchQuery("goodsIntroduction",describe)));
        return getTbGoodsBases(request, builder);
    }

    private List<TbGoodsBasis> getTbGoodsBases(SearchRequest request, SearchSourceBuilder builder) {
        request.source(builder);
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            ArrayList<TbGoodsBasis> goodsBases = new ArrayList<>();
            for (SearchHit hit : response.getHits()) {
                TbGoodsBasis goodsBasis = new TbGoodsBasis();
                goodsBasis.setGoodsId(Integer.valueOf(hit.getId()));
                if (hit.getSourceAsMap() == null) return null;
                loadingLog(goodsBasis, hit.getSourceAsMap());
                goodsBases.add(goodsBasis);

            }
            return goodsBases;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据商品分类查询
     *
     * @param goodsType
     * @return
     */
    @Override
    public List<TbGoodsBasis> getGoodsByType(String goodsType) {
        SearchRequest request = new SearchRequest("tb_goods_basis");
        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("goodsType", goodsType)));
        return getTbGoodsBases(request, builder);
    }

    /**
     * 根据卖家查询
     *
     * @param goodsOwerId
     * @return
     */
    @Override
    public List<TbGoodsBasis> getGoodsBySend(Integer goodsOwerId) {
        SearchRequest request = new SearchRequest("tb_goods_basis");
        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("goodsOwerId", goodsOwerId)));
        return getTbGoodsBases(request,builder);
    }

    /**
     * 根据价格区间查询
     *
     * @param highPrice
     * @param lowPrice
     * @return
     */
    @Override
    public List<TbGoodsBasis> getGoodsByPrice(Double highPrice, Double lowPrice) {
        SearchRequest request = new SearchRequest("tb_goods_basis");
        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.rangeQuery("goodsPrice").gte(lowPrice).lte(highPrice));
        return getTbGoodsBases(request,builder);
    }

    /**
     * 添加一条商品信息记录
     * @param tbGoodsBasis
     * @return
     */
    @Override
    public Boolean addGoods(TbGoodsBasis tbGoodsBasis) {
        IndexRequest request = new IndexRequest("tb_goods_basis","_doc",String.valueOf(MyInterId.getIntegerId()));
        return Dao.getaCreateResult(request, JSON.toJSONString(tbGoodsBasis), client);
    }



    /**
     * 通过商品Id删除一条商品记录
     * @param goodsId
     * @return
     */
    @Override
    public Boolean deleteGoodsById(Integer goodsId) {
        DeleteRequest request = new DeleteRequest("tb_goods_basis",String.valueOf(goodsId));
        try {
            DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
            return response.getResult().toString().equalsIgnoreCase("deleted");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过商品Id修改商品信息,其id和修改后的信息一同封装在 TbGoodsBasis中
     * @param tbGoodsBasis
     * @return
     */
    @Override
    public Boolean updateGoodsById(TbGoodsBasis tbGoodsBasis) {
        UpdateRequest request = new UpdateRequest("tb_goods_basis", String.valueOf(tbGoodsBasis.getGoodsId()));
        HashMap<String, Object> hashMap = new HashMap<>();
        if (tbGoodsBasis.getGoodsName() != null) hashMap.put("goodsName",tbGoodsBasis.getGoodsName());
        if (tbGoodsBasis.getGoodsType() != null) hashMap.put("goodsType",tbGoodsBasis.getGoodsType());
        if (tbGoodsBasis.getGoodsPrice() != null) hashMap.put("goodsPrice",tbGoodsBasis.getGoodsPrice());
        if (tbGoodsBasis.getGoodsStock() != null) hashMap.put("goodsStock",tbGoodsBasis.getGoodsStock());
        if (tbGoodsBasis.getGoodsIntroduction() != null) hashMap.put("goodsIntroduction",tbGoodsBasis.getGoodsIntroduction());
        if (tbGoodsBasis.getGoodsOwerId() != null) hashMap.put("goodsOwerId",tbGoodsBasis.getGoodsOwerId());
        request.doc(hashMap);
        try {
            UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
//            System.out.println(response);
            return response.getResult().toString().equalsIgnoreCase("updated");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 填充除goodsId外的其他属性
     *
     * @param tbGoodsBasis
     * @param source
     */
    private void loadingLog(TbGoodsBasis tbGoodsBasis, Map<String, Object> source) {
        System.out.println(source == null);
        tbGoodsBasis.setGoodsName((String) source.get("goodsName"));
        tbGoodsBasis.setGoodsType((String) source.get("goodsType"));
        tbGoodsBasis.setGoodsPrice(Float.valueOf(String.valueOf(source.get("goodsPrice"))));
        tbGoodsBasis.setGoodsStock((Integer) source.get("goodsStock"));
        tbGoodsBasis.setGoodsIntroduction((String) source.get("goodsIntroduction"));
        tbGoodsBasis.setGoodsOwerId((Integer) source.get("goodsOwerId"));
        List<TbGoodsImage> goodsImages = tbGoodsImageService.getImageByGoodsId(tbGoodsBasis.getGoodsId());
        List<String> images = new ArrayList<>();
        for (TbGoodsImage goodsImage : goodsImages) {
            images.add(goodsImage.getImagePath());
        }
        tbGoodsBasis.setImages(images);

    }

    @Autowired
    @Qualifier("tbGoodsImageServiceImpl")
    private TbGoodsImageService tbGoodsImageService;

}
